import React, { useState, useMemo } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel,
  IconButton,
  Menu,
  Chip,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  Paper,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Tooltip,
  Badge
} from '@mui/material';
import {
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Save as SaveIcon,
  Refresh as RefreshIcon,
  Settings as SettingsIcon,
  Code as CodeIcon,
  Storage as StorageIcon,
  Security as SecurityIcon,
  Notifications as NotificationsIcon,
  ExpandMore as ExpandMoreIcon,
  MoreVert as MoreVertIcon,
  Search as SearchIcon,
  Visibility as VisibilityIcon,
  VisibilityOff as VisibilityOffIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { PageHeader } from '@/components/common/PageHeader';
import { configService } from '@/services/configService';
import type { ConfigItem } from '@/types';

interface ConfigFormData {
  key: string;
  value: string;
  description?: string;
  category: string;
  type: 'string' | 'number' | 'boolean' | 'json';
  isSecret: boolean;
  isRequired: boolean;
}

const ConfigCenterPage: React.FC = () => {
  const queryClient = useQueryClient();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [selectedConfig, setSelectedConfig] = useState<ConfigItem | null>(null);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [showSecrets, setShowSecrets] = useState<Record<string, boolean>>({});

  const {
    control,
    handleSubmit,
    reset,
    setValue,
    formState: { errors, isValid }
  } = useForm<ConfigFormData>({
    defaultValues: {
      key: '',
      value: '',
      description: '',
      category: 'application',
      type: 'string',
      isSecret: false,
      isRequired: false
    },
    mode: 'onChange'
  });

  // 获取配置列表
  const { data: configs = [], isLoading } = useQuery({
    queryKey: ['configs'],
    queryFn: () => configService.getConfigs({})
  });

  // 创建配置
  const createConfigMutation = useMutation({
    mutationFn: (data: any) => configService.createConfig(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs'] });
      setCreateDialogOpen(false);
      reset();
    }
  });

  // 更新配置
  const updateConfigMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: any }) => configService.updateConfig(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs'] });
      setEditDialogOpen(false);
      setSelectedConfig(null);
      reset();
    }
  });

  // 删除配置
  const deleteConfigMutation = useMutation({
    mutationFn: (id: string) => configService.deleteConfig(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['configs'] });
    }
  });

  // 获取配置分类
  const categories = useMemo(() => {
    const categorySet = new Set<string>();
    configs.forEach((config: ConfigItem) => {
      if (config.category) {
        categorySet.add(config.category);
      }
    });
    return Array.from(categorySet).sort();
  }, [configs]);

  // 过滤配置
  const filteredConfigs = useMemo(() => {
    return configs.filter((config: ConfigItem) => {
      const matchesSearch = !searchTerm ||
        config.key.toLowerCase().includes(searchTerm.toLowerCase()) ||
        config.description?.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesCategory = selectedCategory === 'all' || config.category === selectedCategory;
      
      return matchesSearch && matchesCategory;
    });
  }, [configs, searchTerm, selectedCategory]);

  // 按分类分组配置
  const groupedConfigs = useMemo(() => {
    const groups: Record<string, ConfigItem[]> = {};
    filteredConfigs.forEach((config: ConfigItem) => {
      const category = config.category || '其他';
      if (!groups[category]) {
        groups[category] = [];
      }
      groups[category].push(config);
    });
    return groups;
  }, [filteredConfigs]);

  const handleCreateConfig = (data: ConfigFormData) => {
    createConfigMutation.mutate(data);
  };

  const handleEditConfig = (config: ConfigItem) => {
    setSelectedConfig(config);
    setValue('key', config.key);
    setValue('value', config.value);
    setValue('description', config.description || '');
    setValue('category', config.category);
    setValue('type', config.type);
    setValue('isSecret', config.isSecret);
    setValue('isRequired', config.isRequired);
    setEditDialogOpen(true);
  };

  const handleUpdateConfig = (data: ConfigFormData) => {
    if (selectedConfig) {
      updateConfigMutation.mutate({
        id: selectedConfig.id,
        data
      });
    }
  };

  const handleDeleteConfig = (config: ConfigItem) => {
    if (window.confirm(`确认删除配置项 "${config.key}"？`)) {
      deleteConfigMutation.mutate(config.id);
    }
  };

  const toggleSecretVisibility = (configId: string) => {
    setShowSecrets(prev => ({
      ...prev,
      [configId]: !prev[configId]
    }));
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'string': return 'primary';
      case 'number': return 'success';
      case 'boolean': return 'warning';
      case 'json': return 'secondary';
      default: return 'default';
    }
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'application': return <SettingsIcon />;
      case 'database': return <StorageIcon />;
      case 'security': return <SecurityIcon />;
      case 'notification': return <NotificationsIcon />;
      default: return <CodeIcon />;
    }
  };

  const formatValue = (config: ConfigItem) => {
    if (config.isSecret && !showSecrets[config.id]) {
      return '***********';
    }
    
    if (config.type === 'json') {
      try {
        return JSON.stringify(JSON.parse(config.value), null, 2);
      } catch {
        return config.value;
      }
    }
    
    return config.value;
  };

  const renderConfigValue = (config: ConfigItem) => {
    const value = formatValue(config);
    const isSecret = config.isSecret;
    const isJson = config.type === 'json';
    
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        {isJson ? (
          <Paper 
            sx={{ 
              p: 1, 
              bgcolor: 'grey.50', 
              maxWidth: 300, 
              overflow: 'hidden'
            }}
          >
            <Typography 
              variant="caption" 
              component="pre" 
              sx={{ 
                fontSize: '0.75rem',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-all'
              }}
            >
              {value}
            </Typography>
          </Paper>
        ) : (
          <Typography 
            variant="body2" 
            sx={{ 
              maxWidth: 200, 
              overflow: 'hidden', 
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              fontFamily: isSecret ? 'monospace' : 'inherit'
            }}
          >
            {value}
          </Typography>
        )}
        
        {isSecret && (
          <IconButton 
            size="small" 
            onClick={() => toggleSecretVisibility(config.id)}
          >
            {showSecrets[config.id] ? <VisibilityOffIcon /> : <VisibilityIcon />}
          </IconButton>
        )}
      </Box>
    );
  };

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="配置中心"
        description="管理系统配置参数和动态配置更新"
        action={
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={() => setCreateDialogOpen(true)}
            >
              新建配置
            </Button>
            <IconButton onClick={(e) => setAnchorEl(e.currentTarget)}>
              <MoreVertIcon />
            </IconButton>
            <Menu
              anchorEl={anchorEl}
              open={Boolean(anchorEl)}
              onClose={() => setAnchorEl(null)}
            >
              <MenuItem onClick={() => {
                queryClient.invalidateQueries({ queryKey: ['configs'] });
                setAnchorEl(null);
              }}>
                <RefreshIcon sx={{ mr: 1 }} />
                刷新配置
              </MenuItem>
            </Menu>
          </Box>
        }
      />

      {/* 搜索和筛选 */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} md={4}>
              <TextField
                fullWidth
                placeholder="搜索配置项名称或描述..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                InputProps={{
                  startAdornment: <SearchIcon sx={{ color: 'text.secondary', mr: 1 }} />
                }}
              />
            </Grid>
            <Grid item xs={12} md={3}>
              <FormControl fullWidth>
                <InputLabel>分类</InputLabel>
                <Select
                  value={selectedCategory}
                  label="分类"
                  onChange={(e) => setSelectedCategory(e.target.value as string)}
                >
                  <MenuItem value="all">全部分类</MenuItem>
                  {categories.map(category => (
                    <MenuItem key={category} value={category}>{category}</MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={5}>
              <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
                <Chip label={`共 ${filteredConfigs.length} 个配置项`} variant="outlined" />
                <Chip 
                  label={`${configs.filter((c: ConfigItem) => c.isSecret).length} 个敏感配置`} 
                  color="warning" 
                  variant="outlined" 
                />
              </Box>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 配置列表 */}
      <Card>
        <CardContent>
          {Object.entries(groupedConfigs).map(([category, categoryConfigs]) => (
            <Accordion key={category} defaultExpanded>
              <AccordionSummary expandIcon={<ExpandMoreIcon />}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  {getCategoryIcon(category)}
                  <Typography variant="h6">{category}</Typography>
                  <Badge badgeContent={categoryConfigs.length} color="primary" />
                </Box>
              </AccordionSummary>
              <AccordionDetails>
                <List>
                  {categoryConfigs.map((config: ConfigItem) => (
                    <ListItem key={config.id} divider>
                      <ListItemText
                        primary={
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                            <Typography variant="subtitle1" sx={{ fontWeight: 'medium' }}>
                              {config.key}
                            </Typography>
                            <Chip 
                              label={config.type} 
                              size="small" 
                              color={getTypeColor(config.type) as any}
                              variant="outlined"
                            />
                            {config.isRequired && (
                              <Chip label="必需" size="small" color="error" variant="outlined" />
                            )}
                            {config.isSecret && (
                              <Chip label="敏感" size="small" color="warning" variant="outlined" />
                            )}
                          </Box>
                        }
                        secondary={
                          <Box>
                            <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                              {config.description || '无描述'}
                            </Typography>
                            {renderConfigValue(config)}
                          </Box>
                        }
                      />
                      <ListItemSecondaryAction>
                        <Box sx={{ display: 'flex', gap: 1 }}>
                          <Tooltip title="编辑">
                            <IconButton 
                              size="small" 
                              onClick={() => handleEditConfig(config)}
                            >
                              <EditIcon fontSize="small" />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="删除">
                            <IconButton 
                              size="small" 
                              onClick={() => handleDeleteConfig(config)}
                              disabled={config.isRequired}
                            >
                              <DeleteIcon fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </ListItemSecondaryAction>
                    </ListItem>
                  ))}
                </List>
              </AccordionDetails>
            </Accordion>
          ))}
        </CardContent>
      </Card>

      {/* 创建配置对话框 */}
      <Dialog
        open={createDialogOpen}
        onClose={() => {
          setCreateDialogOpen(false);
          reset();
        }}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>新建配置项</DialogTitle>
        <form onSubmit={handleSubmit(handleCreateConfig)}>
          <DialogContent>
            <Grid container spacing={2} sx={{ mt: 1 }}>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="key"
                  control={control}
                  rules={{ required: '配置项名称不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="配置项名称"
                      fullWidth
                      error={!!errors.key}
                      helperText={errors.key?.message}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="category"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>分类</InputLabel>
                      <Select {...field} label="分类">
                        <MenuItem value="application">应用配置</MenuItem>
                        <MenuItem value="database">数据库配置</MenuItem>
                        <MenuItem value="security">安全配置</MenuItem>
                        <MenuItem value="notification">通知配置</MenuItem>
                        <MenuItem value="other">其他</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="配置描述"
                      fullWidth
                      multiline
                      rows={2}
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Controller
                  name="type"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>数据类型</InputLabel>
                      <Select {...field} label="数据类型">
                        <MenuItem value="string">字符串</MenuItem>
                        <MenuItem value="number">数字</MenuItem>
                        <MenuItem value="boolean">布尔值</MenuItem>
                        <MenuItem value="json">JSON</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <Box sx={{ display: 'flex', flexDirection: 'column' }}>
                  <Controller
                    name="isSecret"
                    control={control}
                    render={({ field }) => (
                      <FormControlLabel
                        control={<Switch {...field} checked={field.value} />}
                        label="敏感配置"
                      />
                    )}
                  />
                  <Controller
                    name="isRequired"
                    control={control}
                    render={({ field }) => (
                      <FormControlLabel
                        control={<Switch {...field} checked={field.value} />}
                        label="必需配置"
                      />
                    )}
                  />
                </Box>
              </Grid>
              <Grid item xs={12}>
                <Controller
                  name="value"
                  control={control}
                  rules={{ required: '配置值不能为空' }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="配置值"
                      fullWidth
                      multiline
                      rows={3}
                      error={!!errors.value}
                      helperText={errors.value?.message}
                    />
                  )}
                />
              </Grid>
            </Grid>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => { setCreateDialogOpen(false); reset(); }}>
              取消
            </Button>
            <Button
              type="submit"
              variant="contained"
              disabled={!isValid || createConfigMutation.isPending}
            >
              {createConfigMutation.isPending ? '创建中...' : '创建'}
            </Button>
          </DialogActions>
        </form>
      </Dialog>
    </Box>
  );
};

export default ConfigCenterPage;